package com.imcode.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.HostAuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;

/**
 * @author lixiaojian
 * @version 1.0
 * @ClassName ShiroUtil
 * @Description shiro工具类
 * @date 2021/5/8 10:53
 **/
public class ShiroUtil {

    /**
     * 构建SecurityManager
     * @param realm
     */
    public static void createSecurityManager(Realm realm){
        // 1.构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(realm);
        //2、配置缓存
        MemoryConstrainedCacheManager cacheManager = new MemoryConstrainedCacheManager();
        defaultSecurityManager.setCacheManager(cacheManager);//缓存的是授权的所有信息simpleAuthorizationInfo，且随着用户的退出会清楚缓存
        //3、设置SecurityManager环境
        SecurityUtils.setSecurityManager(defaultSecurityManager);
    }

    /**
     * 登入
     * @param username
     * @param password
     * @return
     */
    public static Subject login(String username,String password){
        Subject subject = SecurityUtils.getSubject();
        HostAuthenticationToken token = new UsernamePasswordToken(username, password);
        subject.login(token);
        return subject;
    }
}
